import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:hc_bot_kit/service/service.dart';
import 'package:hc_bot_kit/state.dart';
import 'package:hc_bot_pro/common/speech/service.dart';

import 'package:hc_bot_pro/guide/state.dart';

class GuideController extends GetxController {
  final GuidePageState state;

  GuideController(this.state);

  _initData() async {
    try {
      await EasyLoading.show();
      Get.find<RobotHardwareService>().onNavigationStateChanged =
          listenGuideState;

      await Get.find<RobotHardwareService>().connect();
      await Future.delayed(3.seconds);
      await Get.find<RobotHardwareService>().guide(state.dst);
      say("好的，请跟我来。");
    } catch (e) {
      EasyLoading.showError(e.toString());
      Get.back();
    } finally {
      EasyLoading.dismiss();
      update(["guide"]);
    }
  }

  void onTap() {}

  // @override
  // void onInit() {
  //   super.onInit();
  // }

  @override
  void onReady() {
    super.onReady();
    _initData();
  }

  // @override
  // void onClose() {
  //   super.onClose();
  // }

  void forcePopback() {
    state.canPopback = true;
    Get.back();
  }
}

extension on GuideController {
  Future say(String phase) {
    return Get.find<HCAISpeechService>().tts.say(phase);
  }

  Future<void> listenGuideState(GuideState state) async {
    debugPrint("GuideState: $state");
    switch (state) {
      case GuideState.REACHED:
        {
          final service = Get.find<RobotHardwareService>();
          if (service.lastDestination == this.state.dst) {
            say("""
体验区${this.state.dst}到了。您可以在健康顾问的指导下体验。我回“接待处”了。如果您有需要，可以到那里来找我。
“""");
            await Future.delayed(Duration(seconds: 5));
            service.guide(service.originPoi);
          } else {
            forcePopback();
          }
        }
        break;
      case GuideState.FAILURE:
        forcePopback();
        break;
      default:
        break;
    }
  }
}
